<template>
    <div>
        <el-head>
            <el-form :model="form" label-width="auto" style="display: flex; gap: 16px;">
                <el-form-item label="供应商类别">
                    <el-tree-select v-model="form.category" :data="treeSelectData" filterable clearable
                        check-strictly=true :props="{ value: 'id', label: 'name', children: 'children' }"
                        style="width: 240px">
                        <template #default="{ data }">
                            <span>
                                <el-icon>
                                    <Folder v-if="data.children && data.children.length > 0" />
                                    <Document v-else />
                                </el-icon>
                                {{ data.name }}
                            </span>
                        </template>
                    </el-tree-select>
                </el-form-item>

                <!-- 修复：将 input1 绑定到 form 内，避免零散变量 -->
                <el-input v-model="form.keyword" style="width: 360px; height: 2rem;"
                    placeholder="按供应商编号，供应商名称，联系人，电话，备注等" />

                <el-checkbox v-model="form.status" @change="handleCheck" label="显示禁用供应商" />

                <el-button type="primary" @click="searchForm">查询</el-button>
            </el-form>
        </el-head>

        <el-divider style="margin: 1px 0;" /> <!-- 可通过 margin 调整上下间距 -->
        <el-main>
            <el-item style="gap: 12px; float: right;">
                <el-button type="primary" @click="openAddDialog">新增</el-button>
                <el-button @click="batchClose">禁用</el-button>
                <el-button @click="batchOpen">启用</el-button>
                <el-button>导入</el-button>
                <el-button>导出</el-button>
                <el-button @click="batchDelete">删除</el-button>
            </el-item>

            <!-- 新增对话框 -->
            <!-- 在 <el-main> 内部，<el-item> 之前或之后添加 -->
            <el-dialog v-model="dialogVisible" :title="supplierDialogType ? '新增供应商' : '编辑供应商'" width="60%"
                :before-close="closeDialog">
                <el-form :model="supplierForm" :rules="supplierRules" ref="supplierFormRef">
                    <el-row :gutter="20">

                        <el-col :span="12">
                            <el-form-item label="供应商名称" prop="name" :label-width="formLabelWidth">
                                <el-input v-model="supplierForm.name" />
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="供应商类别" prop="category" :label-width="formLabelWidth">
                                <el-tree-select v-model="supplierForm.category" :data="treeSelectData" filterable
                                    check-strictly clearable
                                    :props="{ value: 'id', label: 'name', children: 'children' }" style="width: 240px">
                                    <template #default="{ data }">
                                        <span>
                                            <el-icon>
                                                <Folder v-if="data.children && data.children.length > 0" />
                                                <Document v-else />
                                            </el-icon>
                                            {{ data.name }}
                                        </span>
                                    </template>
                                </el-tree-select>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">

                        <el-col :span="12">
                            <el-form-item label="余额日期" prop="balanceDate">
                                <el-date-picker v-model="supplierForm.balanceDate" type="date" placeholder="选择日期"
                                    format="YYYY-MM-DD" style="width: 100%;" />
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="期初应付款" prop="initialPayable">
                                <el-input-number v-model="supplierForm.initialPayable" :min="0" :precision="2"
                                    controls-position="right" placeholder="请输入期初应付款" style="width: 240px" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">

                        <el-col :span="12">
                            <el-form-item label="期初预付款" prop="initialAdvance">
                                <el-input-number v-model="supplierForm.initialAdvance" :min="0" :precision="2"
                                    controls-position="right" placeholder="请输入期初预付款" style="width: 240px" />
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="增值税率(%)" prop="taxRate">
                                <el-input-number v-model="supplierForm.taxRate" :min="0" :precision="2"
                                    controls-position="right" style="width: 240px" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">

                        <el-col :span="12">
                            <el-form-item label="纳税人识别号" prop="taxCode" :label-width="formLabelWidth">
                                <el-input v-model="supplierForm.taxCode" />
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="开户银行" prop="bankName" :label-width="formLabelWidth">
                                <el-input v-model="supplierForm.bankName" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">

                        <el-col :span="12">
                            <el-form-item label="银行账号" prop="account" :label-width="formLabelWidth">
                                <el-input v-model="supplierForm.account" />
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="交货方式" prop="deliveryType" :label-width="formLabelWidth">
                                <el-select v-model="supplierForm.deliveryType" placeholder="请选择交货方式"
                                    style="width: 100%;" clearable>
                                    <el-option v-for="item in deliveryTypes" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="业务员" :label-width="formLabelWidth">
                                <el-select v-model="supplierForm.salesman" placeholder="请选择业务员" style="width: 100%;">
                                    <el-option v-for="item in staffList" :key="item.id" :label="item.name"
                                        :value="item.id" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-form-item label="附件" label-position="top">
                        <el-table :data='supplierForm.contacts' border>
                            <el-table-column label="">
                                <template #default="{ $index }">
                                    <el-button @click="addContactRow($index)" link size="small" icon="Plus"
                                        title="添加联系人" />

                                    <el-button @click="removeContact($index)" link size="small" icon="Delete"
                                        title="删除联系人" />
                                </template>
                            </el-table-column>
                            <el-table-column label="联系人">
                                <template #default="scope">
                                    <el-input v-model="scope.row.name" />
                                </template>
                            </el-table-column>

                            <el-table-column label="手机">
                                <template #default="scope">
                                    <el-input v-model="scope.row.phone" @blur="() => checkPhone(scope.$index)" />
                                </template>
                            </el-table-column>

                            <el-table-column label="座机">
                                <template #default="scope">
                                    <el-input v-model="scope.row.fax" />
                                </template>
                            </el-table-column>

                            <el-table-column label="邮箱">
                                <template #default="scope">
                                    <el-input v-model="scope.row.email" placeholder="邮箱地址"
                                        @blur="() => checkEmail(scope.$index)" />
                                </template>
                            </el-table-column>

                            <el-table-column label="联系地址">
                                <template #default="{ row, $index }">
                                    <div class="address-cell" @click="openAddressDialog(row, $index)">
                                        <span v-if="row.address">{{ row.address }}</span>
                                        <span v-else class="placeholder">点击设置地址</span>
                                    </div>
                                </template>
                            </el-table-column>

                            <el-table-column label="首要联系人">
                                <template #default="scope">
                                    <el-select v-model="scope.row.isFirst"
                                        @change="() => setPrimaryByIndex(scope.$index)" placeholder="请选择">
                                        <el-option label="是" :value="1" />
                                        <el-option label="否" :value="0" />
                                    </el-select>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>

                    <el-form-item label="备注">
                        <el-input v-model="supplierForm.remark" type="textarea" :rows="4" />
                    </el-form-item>
                </el-form>

                <template #footer>
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveSupplier">保存</el-button>
                </template>
            </el-dialog>

            <!-- 地址编辑对话框 -->
            <el-dialog v-model="addressDialog.visible" title="编辑联系地址" width="420px" @close="closeAddressDialog">
                <el-form label-position="top">
                    <!-- 省市区级联 -->
                    <el-form-item label="省 / 市 / 区" required>
                        <el-cascader v-model="addressDialog.form.region" :options="regionData" placeholder="请选择省市区"
                            style="width: 100%" size="small" clearable filterable @change="handleRegionChange" />
                    </el-form-item>

                    <!-- 详细地址 -->
                    <el-form-item label="详细地址" required>
                        <el-input v-model="addressDialog.form.detailAddress" placeholder="街道、门牌号、楼栋等" size="small"
                            @input="updateFullAddress" />
                    </el-form-item>
                </el-form>

                <template #footer>
                    <el-button @click="closeAddressDialog">取消</el-button>
                    <el-button type="primary" @click="saveAddress" :loading="confirmLoading">
                        确定
                    </el-button>
                </template>
            </el-dialog>

            <el-item style="display: block; clear: right;">
                <el-scrollbar max-height="400px">
                    <el-table max-height="380px" :data="tableData" style="width: 100%"
                        :header-cell-style="{ position: 'sticky', top: 0, zIndex: 1 }"
                        @selection-change="handleSelection" v-loading="tableLoad">
                        <el-table-column type="selection" width="55px" />

                        <el-table-column label="操作" width="100">
                            <template #default="scope">
                                <el-button @click="editSupplier(scope.row.id)" link size="default" icon="Edit"
                                    title="编辑" />

                                <el-button @click="deleteSupplier(scope.row.id)" link size="default" icon="Delete"
                                    title="删除" />
                            </template>
                        </el-table-column>

                        <el-table-column prop="categoryName" label="供应商类别" width="150" />
                        <el-table-column prop="code" label="供应商编号" width="150" />
                        <el-table-column prop="name" label="供应商名称" width="200" />
                        <el-table-column prop="staffName" label="业务员" width="120" />
                        <el-table-column prop="primaryContactName" label="联系人" width="120" />
                        <el-table-column prop="taxRate" label="增值税税率(%)" width="120" />
                        <el-table-column prop="account" label="银行账号" width="180" />
                        <el-table-column prop="bankName" label="开户银行" width="180" />
                        <el-table-column prop="taxCode" label="纳税人识别号" width="180" />
                        <el-table-column prop="primaryContactPhone" label="手机" width="120" />
                        <el-table-column prop="primaryContactFax" label="座机" width="120" />
                        <el-table-column prop="primaryContactEmail" label="邮箱地址" width="200" />
                        <el-table-column prop="primaryContactAddress" label="联系地址" width="250" />
                        <el-table-column prop="remark" label="备注" width="150" />
                        <el-table-column prop="paymentBalance" label="应付余额(元)" width="120" />
                        <el-table-column prop="status" label="状态" width="100">
                            <template #default="scope">
                                <el-switch :model-value="scope.row.status" :active-value="1" :inactive-value="0"
                                    @change="handleStatus(scope.row)" />
                            </template>
                        </el-table-column>

                    </el-table>
                </el-scrollbar>
                <!-- 分页 -->
                <div class="demo-pagination-block" style="float: right;">
                    <el-pagination v-model:current-page="pageInfo.pageNum" v-model:page-size="pageInfo.pageSize"
                        :page-sizes="[5, 10, 15, 20]" :background="true"
                        layout="total, sizes, prev, pager, next, jumper" :total="pageInfo.total"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                </div>
            </el-item>
        </el-main>
    </div>
</template>

<script setup>

import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { regionData, codeToText } from 'element-china-area-data'
import axios from 'axios';

const formLabelWidth = '100px'

const tableLoad = ref(false)

const confirmLoading = ref(false)

const saving = ref(false)

const supplierFormRef = ref()

/// 对话框（添加）
// 控制新增对话框显隐
const dialogVisible = ref(false);
const supplierDialogType = ref(true)


const pageInfo = reactive({
    total: 0,
    pageSize: 5,
    pageNum: 1,
})

// 表单数据(供应商搜索)
const form = reactive({
    category: null,
    keyword: '',
    status: 1,
});

// 表单数据
const supplierForm = reactive({
    id: null,
    code: '',
    name: '',
    category: '',
    balanceDate: null,
    initialPayable: '',
    initialAdvance: '',
    taxRate: '',
    taxCode: '',
    bankName: '',
    account: '',
    deliveryType: '',
    salesman: '',
    remark: '',

    contacts: [
        { id: null, name: '', phone: '', fax: '', email: '', address: '', isFirst: null }
    ]
});

// 供应商类别
const supplierTypeList = ref([])

// 获取供应商类别
const getSupplierType = async () => {
    const res = await axios.get('/api/basic/supplier/allSupplierType')
    if (res.data.code === 5200) {
        supplierTypeList.value = res.data.supplierTypeList
    } else {
        ElMessage.error("供应商类别数据获取失败")
    }
}

// 构建树形数据
const treeData = computed(() => {
    const roots = []

    const map = {}

    supplierTypeList.value.forEach(item => {
        map[item.id] = { ...item, children: [] }
    })

    supplierTypeList.value.forEach(item => {
        if (item.parentId === null || item.parentId === '0') {
            roots.push(map[item.id])
        } else {
            const parentObj = map[item.parentId]
            if (parentObj) {
                parentObj.children.push(map[item.id])
            }
        }
    })
    return roots
})

// 树形选择器
const treeSelectData = computed(() => {
    const enabledTreeData = treeData.value
    return [
        {
            id: '0',
            name: '全部',
            children: enabledTreeData
        }
    ]
})

// 表格数据
const tableData = ref([]);

// 获取供应商信息
const getSupplierList = async () => {
    tableLoad.value = true;
    try {
        const params = {
            pageNum: pageInfo.pageNum,
            pageSize: pageInfo.pageSize,
            ...form
        }

        const res = await axios.get('/api/basic/supplier/supplierByPage', { params })
        if (res.data.code === 5200) {
            tableData.value = res.data.pageInfo.list
            pageInfo.total = res.data.pageInfo.total
            pageInfo.pageNum = res.data.pageInfo.pageNum
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    } finally {
        tableLoad.value = false
    }
}

// 业务员
const staffList = ref([])

const getStaffList = async () => {
    try {
        const res = await axios.get('/api/basic/enterprise/allStaff')
        if (res.data.code === 5200) {
            staffList.value = res.data.staffList
        } else {
            ElMessage.error(res.data.message)
        }
    } catch (error) {
        console.error('加载业务员列表失败:', error)
        ElMessage.error('加载业务员列表失败: ' + (error.response?.data?.msg || error.message))
    }
}


const deliveryTypes = [
    { value: '1', label: '快递物流' },
    { value: '2', label: '自配送' },
    { value: '3', label: '自提' },
    { value: '4', label: '其他' }
]
// 多选框：显示禁用数据
const handleCheck = (checked) => {
    form.status = checked ? null : 1
    getSupplierList()
}

// 页容量发生改变
const handleSizeChange = (val) => {
    pageInfo.pageSize = val
    pageInfo.pageNum = 1
    getSupplierList()
}

// 页码发生改变
const handleCurrentChange = (val) => {
    pageInfo.pageNum = val
    getSupplierList()
}
// 查询方法
const searchForm = () => {
    pageInfo.pageNum = 1
    getSupplierList()
}

// 地址对话框
const addressDialog = reactive({
    visible: false,
    currentContact: null,
    currentIndex: -1,
    form: {
        region: [],
        detailAddress: '',
        fullAddress: '',
    }
})

// 关闭对话框前
const closeDialog = (done) => {
    ElMessageBox.confirm('当前有未保存的内容，确定关闭吗？')
        .then(() => {
            restSupplierForm()
            done()
        })
        .catch(() => {
        })
}

// 在当前行后添加联系人
const addContactRow = (index) => {
    supplierForm.contacts.splice(index + 1, 0, {
        name: '',
        phone: '',
        fax: '',
        email: '',
        address: '',
        isFirst: null
    })
}

// 删除联系人
const removeContact = (index) => {
    if (supplierForm.contacts.length > 1) {
        supplierForm.contacts.splice(index, 1)
        ElMessage.success('联系人已删除')
    } else {
        ElMessage.warning('至少需要保留一个联系人')
    }
}

// 设置首要联系人
const setPrimaryByIndex = (index) => {
    supplierForm.contacts.forEach((item, i) => {
        item.isFirst = (i === index) ? 1 : 0;
    });
};


// 打开地址对话框
const openAddressDialog = (contact, index) => {
    addressDialog.currentContact = contact
    addressDialog.currentIndex = index

    if (contact.address) {
        const parsedData = parseExistingAddress(contact.address)
        addressDialog.form = {
            region: parsedData.region || [],
            detailAddress: parsedData.detailAddress || '',
            fullAddress: contact.address
        }
    } else {
        addressDialog.form = {
            region: [],
            detailAddress: '',
            fullAddress: ''
        }
    }
    addressDialog.visible = true
}

// 解析现有地址
const parseExistingAddress = (address) => {
    if (!address) return { region: [], detailAddress: '' }

    try {
        const parts = address.split(' ')
        if (parts.length >= 3) {
            const provinceName = parts[0]
            const cityName = parts[1]
            const districtName = parts[2]
            const detailAddress = parts.slice(3).join(' ') || ''

            const regionCodes = findRegionCodes(provinceName, cityName, districtName)
            return { region: regionCodes, detailAddress }
        }
        return { region: [], detailAddress: address }
    } catch (error) {
        return { region: [], detailAddress: address }
    }
}

// 查找地区代码
const findRegionCodes = (provinceName, cityName, districtName) => {
    try {
        for (const province of regionData) {
            if (codeToText[province.value] === provinceName) {
                if (province.children) {
                    for (const city of province.children) {
                        if (codeToText[city.value] === cityName) {
                            if (city.children) {
                                for (const district of city.children) {
                                    if (codeToText[district.value] === districtName) {
                                        return [province.value, city.value, district.value]
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return []
    } catch (error) {
        return []
    }
}

// 安全处理地区选择变化
const handleRegionChange = (value) => {
    try {
        addressDialog.form.region = Array.isArray(value) ? value : []
        updateFullAddress()
    } catch (error) {
        console.error('处理地区选择变化失败:', error)
        addressDialog.form.region = []
    }
}

// 更新完整地址
const updateFullAddress = () => {
    try {
        const { region, detailAddress } = addressDialog.form

        addressDialog.form.fullAddress = detailAddress || ''

        if (!region || region.length !== 3) {
            return
        }

        const provinceCode = region[0]
        const cityCode = region[1]
        const districtCode = region[2]

        if (!provinceCode || !cityCode || !districtCode) {
            return
        }

        const province = codeToText[provinceCode] || ''
        const city = codeToText[cityCode] || ''
        const district = codeToText[districtCode] || ''

        if (!province || !city || !district) {
            return
        }

        const regionText = `${province} ${city} ${district}`
        addressDialog.form.fullAddress = detailAddress ?
            `${regionText} ${detailAddress}`.trim() : regionText

    } catch (error) {
        console.error('生成完整地址失败:', error)
        addressDialog.form.fullAddress = addressDialog.form.detailAddress || ''
    }
};

// 保存地址
const saveAddress = async () => {
    try {

        confirmLoading.value = true

        if (!addressDialog.form.region || addressDialog.form.region.length !== 3) {
            ElMessage.error('请选择完整的省市区')
            return
        }

        if (!addressDialog.form.detailAddress?.trim()) {
            ElMessage.error('请输入详细地址')
            return
        }

        if (addressDialog.currentContact) {
            Object.assign(addressDialog.currentContact, {
                address: addressDialog.form.fullAddress.trim()
            })
            ElMessage.success('地址保存成功');
            closeAddressDialog();
        }
    } catch (error) {
        console.error('保存地址失败:', error);
        ElMessage.error('保存失败: ' + error.message);
    } finally {
        confirmLoading.value = false
    }
}

// 关闭地址对话框
const closeAddressDialog = () => {
    addressDialog.visible = false;
    // 新增：重置地址表单
    addressDialog.form = { region: [], detailAddress: '', fullAddress: '' };
};


// 校验供应商名称
const checkName = (rule, value, callback) => {
    if (!value || value.trim() === '') {
        return callback(new Error('请输入供应商名称'))
    }
    callback()
}

// 校验供应商类别
const checkCategory = (rule, value, callback) => {
    if (!value) {
        return callback(new Error('请选择供应商类别'))
    }
    callback()
}

// 校验交货方式
const checkDeliveryType = (rule, value, callback) => {
    // deliveryType 是 el-select，value 是字符串，不能是 null/空字符串
    if (!value || value.trim() === '') {
        return callback(new Error('请选择交货方式'))
    }
    callback()
}

// 校验余额日期
const checkBalanceDate = (rule, value, callback) => {
    // balanceDate 是 el-date-picker，value 是日期对象或字符串
    if (!value) {
        return callback(new Error('请选择余额日期'))
    }
    callback()
}


// 手机号正则
const phonePattern = /^1[3-9]\d{9}$/
// 邮箱正则
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

// 联系人手机校验
const checkPhone = (index) => {
    const value = supplierForm.contacts[index]?.phone

    if (!value || value.trim() === '') {
        return true
    }
    if (!phonePattern.test(value)) {
        ElMessage.warning('请输入正确的手机号码')
        return false
    }
    return true
}

// 联系人邮箱校验
const checkEmail = (index) => {
    const value = supplierForm.contacts[index]?.email
    if (!value || value.trim() === '') {
        return true
    }
    if (!emailPattern.test(value)) {
        ElMessage.warning('请输入正确的邮箱地址')
        return false
    }
    return true
}

const supplierRules = reactive({
    name: [{ validator: checkName, trigger: 'blur' }],
    category: [{ validator: checkCategory, trigger: 'change' }],
    balanceDate: [{ validator: checkBalanceDate, trigger: 'change' }],
    deliveryType: [{ validator: checkDeliveryType, trigger: 'change' }],
})

// 打开新增对话框
const openAddDialog = async () => {
    supplierDialogType.value = true
    restSupplierForm()
    dialogVisible.value = true;
    await getStaffList()
};

// 编辑供应商
const editSupplier = async (id) => {
    supplierDialogType.value = false

    try {
        const res = await axios.get('/api/basic/supplier/supplierById', { params: { id: id } })
        if (res.data.code === 5200) {
            const supplierResponse = res.data.supplierResponse
            const supplier = supplierResponse.supplier
            const contactList = supplierResponse.contactList

            Object.assign(supplierForm, {
                id: supplier.id,
                name: supplier.name || '',
                category: supplier.category || '',
                balanceDate: supplier.balanceDate || null,
                initialPayable: supplier.initialPayable || '',
                initialAdvance: supplier.initialAdvance || '',
                taxRate: supplier.taxRate || '',
                taxCode: supplier.taxCode || '',
                bankName: supplier.bankName || '',
                account: supplier.account || '',
                deliveryType: supplier.deliveryType || '',
                salesman: supplier.salesman || '',
                remark: supplier.remark || '',
                contacts: contactList.map(c => ({
                    id: c.id,
                    name: c.name,
                    phone: c.phone,
                    fax: c.fax,
                    email: c.email,
                    address: c.address,
                    isFirst: c.isFirst
                }))
            })
            await getStaffList()
            dialogVisible.value = true
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    }
}


// 保存供应商信息
const saveSupplier = async () => {
    try {
        await supplierFormRef.value.validate()

        // 检查联系人信息
        let hasError = false;
        supplierForm.contacts.forEach((contact, index) => {
            if (!checkPhone(index)) hasError = true;
            if (!checkEmail(index)) hasError = true;
        });
        if (hasError) {
            return;
        }

    } catch (error) {
        ElMessage.error('请检查表单填写是否正确')
        return
    }

    // 过滤空联系人
    const validContacts = supplierForm.contacts.filter(contact =>
        contact.name || contact.phone || contact.fax || contact.email || contact.address
    )

    // 检查是否至少有一个有效联系人
    if (validContacts.length === 0) {
        ElMessage.warning('请至少添加一个有效的联系人信息')
        return
    }

    // 检查是否有首要联系人
    const hasPrimary = validContacts.some(contact => contact.isFirst === 1)
    if (!hasPrimary && validContacts.length > 0) {
        // 如果没有设置首要联系人，自动设置第一个为首要
        validContacts[0].isFirst = 1
        ElMessage.info('已自动设置第一个联系人为首要联系人')
    }

    // 构造请求体 - 匹配后端的CustomerRequest结构
    const supplierRequest = {
        supplier: {
            id: supplierForm.id,
            code: supplierForm.code,
            name: supplierForm.name,
            category: supplierForm.category,
            balanceDate: supplierForm.balanceDate,
            initialPayable: supplierForm.initialPayable || 0,
            initialAdvance: supplierForm.initialAdvance || 0,
            taxRate: supplierForm.taxRate,
            taxCode: supplierForm.taxCode,
            bankName: supplierForm.bankName,
            account: supplierForm.account,
            deliveryType: supplierForm.deliveryType,
            salesman: supplierForm.salesman,
            remark: supplierForm.remark,
        },
        contactList: validContacts.map(contact => ({
            id: contact.id,
            name: contact.name || '',
            phone: contact.phone || '',
            fax: contact.fax || '',
            email: contact.email || '',
            address: contact.address || '',
            isFirst: contact.isFirst === 1 ? 1 : 0
        }))
    }

    try {

        saving.value = true

        const url = supplierDialogType.value ? '/api/basic/supplier/addSupplier' : '/api/basic/supplier/updateSupplier'

        const res = await axios.post(url, supplierRequest)
        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
            dialogVisible.value = false
            restSupplierForm()
            // 刷新列表
            pageInfo.pageNum = 1
            getSupplierList()
        } else {
            ElMessage.error(res.data.message || '创建失败')
        }
    } catch (error) {
        console.error('创建供应商失败:', error)
        ElMessage.error('创建失败: ' + (error.response?.data?.message || error.message))
    } finally {
        saving.value = false
    }
}

// 表单重置
const restSupplierForm = () => {
    supplierFormRef.value?.resetFields()
    // 清空 contacts 数组并 push 新对象，保持响应式
    supplierForm.contacts.length = 0
    supplierForm.contacts.push({
        id: null, name: '', phone: '', fax: '', email: '', address: '', isFirst: null
    })
}

// 选中的对象
const selections = ref([])

// 选中的id
const selectionIds = computed(() => selections.value.map(item => item.id))

// 多选框变化
const handleSelection = (selection) => {
    selections.value = selection
}

// 切换状态
const handleStatus = async (row) => {
    tableLoad.value = true
    supplierDialogType.value = true
    const originalStatus = row.status
    try {
        const res = await axios.post("/api/basic/supplier/updateSupplierStatus", null, { params: { id: row.id, status: originalStatus === 1 ? 0 : 1 } })
        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
            await getSupplierList()
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    } finally {
        tableLoad.value = false
    }
}

// 批量禁用
const batchClose = async () => {
    if (selectionIds.value.length === 0) {
        ElMessage.warning('请先选择')
        return
    }
    await batchUpdateStatus(0)
}

// 批量启用
const batchOpen = async () => {
    if (selectionIds.value.length === 0) {
        ElMessage.warning('请先选择')
        return
    }
    await batchUpdateStatus(1)
}

// 批量修改状态
const batchUpdateStatus = async (status) => {

    const params = {
        ids: selectionIds.value,
        status
    }

    try {
        const res = await axios.post("/api/basic/supplier/batchUpdateSupplierStatus", params)
        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
            await getSupplierList()
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    }
}

// 删除
const deleteSupplier = async (id) => {
    try {
        const res = await axios.post("/api/basic/supplier/deleteSupplier", null, { params: { id } })
        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
            await getSupplierList()
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    }
}


// 批量删除
const batchDelete = async () => {
    try {
        const res = await axios.post("/api/basic/supplier/batchDeleteSupplier", selectionIds.value)
        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
            await getSupplierList()
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    }
}


onMounted(() => {
    getSupplierType()
    getSupplierList()
})

</script>

<style scoped>
/* 隔行变色样式（保持不变） */
:deep(.el-table .el-table__row.table-row-even) {
    background-color: #f5f7fa;
}

:deep(.el-table .el-table__row.table-row-odd) {
    background-color: #ffffff;
}

/* 关键修复：强化 hover 样式优先级 */
/* 1. 直接针对表格行的 hover 状态，叠加父级选择器提高权重 */
:deep(.el-table tbody .el-table__row:hover > td) {
    background-color: #fff9e6 !important;
    /* 浅黄色 */
}

/* 2. 额外覆盖 Element Plus 内置的 hover 类（防止动态添加的类覆盖） */
:deep(.el-table .el-table__row.hover-row > td) {
    background-color: #fff9e6 !important;
}

.scrollbar-demo-item {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 50px;
    margin: 10px;
    width: 2000px;
    text-align: center;
    border-radius: 4px;
    background: var(--el-color-primary-light-9);
    color: var(--el-color-primary);
}
</style>